<?php namespace DH16\Tools;
use PDO;
use Exception;
/**
 * Class Model
 * 模型类
 */
class Model
{
	private static $pdo = null;

	//连接数据库
	public function __construct()
	{
		if (is_null(self::$pdo)) {
			try {
				//数据源
				$dsn = 'mysql:host='.C('DB_HOST').';dbname='.C('DB_NAME');
				//用户名,密码
				$username = C('DB_USER');
				$password = C('DB_PSD');
				//实例化pdo
				self::$pdo = new Pdo($dsn, $username, $password);
				//设置字符集
				self::$pdo->query('set names utf8');
				//设置错误属性
				self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			} catch (Exception $e) {
				die("<h1 style='color: red'>" . $e->getMessage() . "</h1>");
			}
		}
	}

	//查询
	public function query($sql)
	{
		try {
			//返回的是有结果集的数据操作
			$result = self::$pdo->query($sql);
			$rows = $result->fetchAll(PDO::FETCH_ASSOC);
			return $rows;
		} catch (Exception $e) {
			echo "<h1 style='color: red'>" . $e->getMessage() . "</h1>";
		}
	}

	//增删改方法
	public function exec($sql)
	{
		try {
			//返回受影响的条数(无结果集的数据操作)
			$rows = self::$pdo->exec($sql);
			return "<h1 style='color: deepskyblue'>受影响的条数:" . $rows . "条</h1>";
		} catch (Exception $e) {
			echo "<h1 style='color: red'>" . $e->getMessage() . "</h1>";
		}
	}
}


